<template>
    <div>
      <!-- <canvas id="canvas" width="800" height="600" ></canvas> -->
      <div class="ls_maincont"></div>
      <div class="mainDiv hjm_c">
        <div class="r" style="flex-direction: column; align-items: center; flex: 1">
          <div class="stage_c_r main_3 hjm_zhjl_item" style="width: 100%">
            <div class="t">
              <div class="react">
                <i class="l_up"></i>
                <i class="l_down"></i>
                <i class="r_up"></i>
                <i class="r_down"></i>
                <div class="title">
                  <span>{{ currentTag }}层燃烧器着火距离监测</span>
                </div>
              </div>
            </div>
            <el-carousel ref="carouselRef" indicator-position="outside" style="flex: 1" class="d d2" :interval="30000" :pause-on-hover="false" :autoplay="true" @change="changeIndex">
              <el-carousel-item v-for="i in [0, 1, 2, 3]" :key="i" style="width: 100%   ">
                <div class="d d2" style="width: 100%;  ">
                  <div style="
                    display: flex;
                    width: 683px;
                    color: #343434;
                    font-size: 36px;
                    justify-content: space-between;
                    position: absolute;
                  ">
                    <span>左墙</span>
                    <span>右墙</span>
                  </div>
                  <div style="
                    display: flex;
                    color: #343434;
                    font-size: 30px;
                    position: absolute;
                    top: 14px;
                  ">
                    <span  >后墙</span>
                     <!-- <div>{{ pianyiliang.s }}</div> -->
                  </div>
                 <!-- 偏移量 -->
                  <div style="
                    display: flex;
                    color: #343434;
                    font-size: 34px;
                    position: absolute;
                    top: 440px;
                  ">
                    <span>前墙</span>
                  </div>
                  <div class="hjm_zhjl">
                    <div class="l_t l_d">
                      <div class="dengpao"></div>
                      <div class="pointer_name">
                        <div style="text-align: center;"> {{ currentTag }}1</div>
                        <div> 着火距离：{{ distanceMap[1].v }} mm </div>
                        <div> 燃烧温度：{{ distanceMap[1].t }} ℃ </div>
                        <div style="font-size: 20px;"> 燃烧稳定性：{{ distanceMap[1].s }} % </div>
                      </div>
                      <div class="pentou"></div>
                    </div>
                    <div class="l_t">
                      <div class="pentou"></div>
                      <div class="pointer_name">
                        <div style="text-align: center;"> {{ currentTag }}2</div>
                        <div> 着火距离：{{ distanceMap[2].v }} mm </div>
                        <div> 燃烧温度：{{ distanceMap[2].t }} ℃ </div>
                        <div style="font-size: 20px;"> 燃烧稳定性：{{ distanceMap[2].s }} % </div>
                      </div>
                      <div class="dengpao"></div>
                    </div>
                    <div class="l_t r_t">
                      <div class="pentou"></div>
                      <div class="pointer_name">
                        <div style="text-align: center;"> {{ currentTag }}3</div>
                        <div> 着火距离：{{ distanceMap[3].v }} mm </div>
                        <div> 燃烧温度：{{ distanceMap[3].t }} ℃ </div>
                        <div style="font-size: 20px;"> 燃烧稳定性：{{ distanceMap[3].s }} % </div>
                      </div>
                      <div class="dengpao"></div>
                    </div>
                    <div class="l_t l_d r_d">
                      <div class="dengpao"></div>
                      <div class="pointer_name">
                        <div style="text-align: center;"> {{ currentTag }}4</div>
                        <div> 着火距离：{{ distanceMap[4].v }} mm </div>
                        <div> 燃烧温度：{{ distanceMap[4].t }} ℃ </div>
                        <div style="font-size: 20px;"> 燃烧稳定性：{{ distanceMap[4].s }} % </div>
                      </div>
                      <div class="pentou"></div>
                    </div>
                    <div class="c">
                      <div class="c_1"  style=" position: relative;">
                        <div class="axis x-axis"></div>
                        <div class="axis y-axis"></div>
                        <div   style="position: absolute;  top: 183px;   left: 200px;   font-size: 18px" >{{ pianyiliang.s }}</div>
                      </div>
                      <div class="c_2" :id="`huoYanDiv_${tagArr[i]}`">
                      </div>
                      <div class="c_3">
                        <div class="c_31"><img src="../assets/hjmsft2_1.png" /></div>
                        <div class="c_32"><img src="../assets/hjmsft2_1.png" /></div>
                        <div class="c_33"><img src="../assets/hjmsft2_1.png" /></div>
                        <div class="c_34"><img src="../assets/hjmsft2_1.png" /></div>
                      </div>
                    </div>
                  </div>
                </div>
              </el-carousel-item>
            </el-carousel>
          </div>
         
        </div>
        <div class="r">
          <div class="d" id="zbf_hjm_btns">
            <span v-for="item in dianwei" :key="item.key" @click="toDianJi(item.key)"  :class="{ active: currentTag === item.key }" style="font-size: 30px;">{{ item.value }}</span>
          </div>
        </div>
      </div>
      <div class="stage_t">
        <a href="#"></a>
        <h1>1号锅炉燃烧数字化与低负荷稳燃监测管理系统</h1>
        <div>
          <span></span>
          <span id="todayTimer">{{ nowTime }}</span>
        </div>
      </div>
    </div>
  </template>
  
  
  
  <script setup>
  import { ref, onMounted, reactive } from "vue";
  import { formatTime } from "../utils/date.js";
  import { useRoute, useRouter } from "vue-router";
  import axios from "axios";
  import { field } from '../api/hjm.js'
  import * as THREE from "three";
  import frame0 from "../assets/huomiao/frame_0.png";
  import frame1 from "../assets/huomiao/frame_1.png";
  import frame2 from "../assets/huomiao/frame_2.png";
  import frame3 from "../assets/huomiao/frame_3.png";
  
  const router = useRouter();
  const nowTime = ref("");
  
  let dianwei = ref([
    { key: 'A', value: 'A层燃烧器' },
    { key: 'B', value: 'B层燃烧器' },
    { key: 'C', value: 'C层燃烧器' },
    { key: 'D', value: 'D层燃烧器' },
    // { key: 'E', value: 'E层燃烧器' },
    // { key: 'F', value: 'F层燃烧器' },
    // { key: 'G', value: 'G层燃烧器' },
    // { key: 'S', value: '燃尽风层' },
  ])
  
  
  const currentTag = ref('A');
  onMounted(() => {
    setInterval(() => {
      nowTime.value = formatTime(new Date());
    });
    dianji("A")
    tagArr.value.forEach(tag => createSDScene(tag))
  });
  
  
  const tagArr = ref(['A', 'B', 'C', 'D']);
  const changeIndex = (activedIndex) => {
    currentTag.value = tagArr.value[activedIndex]
    dianji(currentTag.value);
  }
  let pianyiliang=reactive({});
  const distanceMap = reactive({
    1: {},
    2: {},
    3: {},
    4: {},
  })
  
  const offsetMap = reactive({})
  const carouselRef = ref()
  const toDianJi = (tag) => {
    let index = tagArr.value.indexOf(tag)
    carouselRef.value.setActiveItem(index)
    dianji(tag)
  }
  let dianji = async (tag) => {
    currentTag.value = tag
    // 修改向后台请求数据时的参数。 燃尽风为"S"
    if (tag === "燃尽风层") tag = "S"
    let res = await field(tag)
    if (res.status === 200) {
      pianyiliang=res.data.offset
      offsetMap[tag] = res.data.offset
      // 设置着火距离监测面板的值和火焰大小
      // const arr = [2, 3, 4, 1]
      // arr.forEach(index => {
      //   let item  = 
      // })
      // 温度：左上index0 右上index5 左下index30 右下index35
      let TMap = { 1: 30, 2: 0, 3: 5, 4: 35 }
      // 遍历数据源
      res.data.distances.forEach((item, index) => {
        let no = Number(item.parameter[1])
        item.v = item.v === null ? 0 : item.v
        // distanceMap[no] = { v: item.v, s:item.stability, t: res.data.field66 ? res.data.field66[TMap[no]] : 0 }
        // distanceMap[no] = { v: item.v, t: res.data.field66[TMap[no]]}
        distanceMap[no] = { v: item.v, s: item.stability, t: res.data.field66 ? res.data.field66[TMap[no]] : 0 }
        // 调整火焰顺序, 1234 -> 2341
        index = index - 1
        if (index < 0) index = 3
        // 调整火焰的大小
        console.debug('当前数据：', tag, index, item.v / 800, item.v / 1200, group[tag]['scale'])
        group[tag].children[index].scale.set(item.v / 800, item.v / 1200)
      })
      // 设置截面温度场分布面板的值和背景色
      // const elArr = document.querySelectorAll("#_c>.hjm_wd_block>span")
      // res.data.field66.forEach((value, index) => {
      //   elArr[index].innerText = value
      //   let color = calculateColor(value)
      //   elArr[index].style.backgroundColor = `rgb(${color[0]}, ${color[1]}, ${color[2]})`
      // })
    }
  };
  
  
  let group = {}
  let createSDScene = function (currentTag) {
    // 创建一个场景
    const scene = new THREE.Scene();
    // 创建一个相机
    const camera = new THREE.PerspectiveCamera(50, 410 / 366, 0.1, 10000);
    camera.position.z = 400;
  
    // 创建空心圆
    var circleGeometry = new THREE.CircleGeometry(5, 32);
    var circleMaterial = new THREE.MeshBasicMaterial({ color: 0x666666, side: THREE.DoubleSide });
    var circleMesh = new THREE.Mesh(circleGeometry, circleMaterial);
    scene.add(circleMesh);
  
    // 创建一个渲染器
    const renderer = new THREE.WebGLRenderer({ alpha: true });
    renderer.setSize(410, 366);
    let canvasEl = document.querySelector(`#huoYanDiv_${currentTag} > canvas`)
    if (canvasEl) {
      canvasEl.parentNode.removeChild(canvasEl);
    }
    document.getElementById(`huoYanDiv_${currentTag}`).appendChild(renderer.domElement);
  
    // 创建火焰
    group[currentTag] = new THREE.Group();
    const textures = [];
    const loader = new THREE.TextureLoader();
    Promise.all([
      new Promise((resolve) => {
        loader.load(frame0, function (texture) {
          textures.push(texture);
          // 创建四个火焰
          const geometry = new THREE.PlaneGeometry(150, 75);
          geometry.translate(150 / 2, 0, 0);
          const material = new THREE.MeshBasicMaterial({ map: texture, transparent: true });
          const plane0 = new THREE.Mesh(geometry, material);
          group[currentTag].add(plane0);
  
          let unitX = 207;
          let unitY = 190;
          // 右上
          const plane1 = plane0.clone();
          plane1.rotation.z = (-Math.PI * 11 / 36) * 3;
          plane1.position.set(unitX - 8, unitY - 10, 0);
          group[currentTag].add(plane1);
          // 右下
          const plane2 = plane0.clone();
          plane2.rotation.z = (Math.PI * 8 / 36) * 3;
          plane2.position.set(unitX - 6, -unitY + 18, 0);
          group[currentTag].add(plane2);
          // 左下
          const plane3 = plane0.clone();
          plane3.rotation.z = Math.PI * 5 / 36;
          plane3.position.set(-unitX + 8, -unitY + 18, 0);
          group[currentTag].add(plane3);
          // 左上
          plane0.rotation.z = -Math.PI * 12 / 36;
          plane0.position.set(-unitX + 8, unitY - 8, 0);
          resolve(true);
        });
      }),
      new Promise((resolve) => {
        loader.load(frame1, (texture) => {
          textures.push(texture);
          resolve(true);
        });
      }),
      new Promise((resolve) => {
        loader.load(frame2, (texture) => {
          textures.push(texture);
          resolve(true);
        });
      }),
      new Promise((resolve) => {
        loader.load(frame3, (texture) => {
          textures.push(texture);
          resolve(true);
        });
      }),
    ])
      .then(() => {
        scene.add(group[currentTag]);
         // 创建偏离实心圆
        var circleGeometryOffset = new THREE.CircleGeometry(10, 32);
        var circleMaterialOffset = new THREE.MeshBasicMaterial({ color: 0x000000, side: THREE.DoubleSide });
        var circleMeshOffset = new THREE.Mesh(circleGeometryOffset, circleMaterialOffset);
        scene.add(circleMeshOffset);
        // 动画循环
        let frameIndex = 0;
        setInterval(() => {
          // 更新纹理
          group[currentTag].children.forEach((plane) => {
            plane.material.map = textures[frameIndex];
          });
          // 更新帧索引
          frameIndex = (frameIndex + 1) % 4;
          if (offsetMap[currentTag]) {
            let x = offsetMap[currentTag].x - 205;
            let y = offsetMap[currentTag].y - 183;
            // 测试可修改此处
            // x = -100
            // y = -40
            circleMeshOffset.position.set(x, y, )
            for (let i = 0; i < 4; i++) {
              let plane = group[currentTag].children[i]
              let positionX = plane.position.x
              let positionY = plane.position.y
              let positions=plane.position.s
              let jiaodu = Math.atan2(positionY - y, positionX - x)
              plane.rotation.z = jiaodu + Math.PI
            }
          };
          // 渲染场景
          renderer.render(scene, camera);
        }, 100);
      })
      .catch((error) => {
        console.error("One of the promises rejected:", error);
      });
  };
  </script>
  
  
  
  
  
  
  <style lange="scss" scoped>
  #zbf_hjm_btns {
    flex-wrap: wrap;
  
    >span {
      width: calc((100% - 240px) / 4);
    }
  }
  
  .hjm_zhjl .l_t:nth-child(1),
  .hjm_zhjl .l_t:nth-child(2) {
    .pointer_name {
      position: relative;
      left: -77px;
    }
  }
  
  .hjm_zhjl .l_t:nth-child(3),
  .hjm_zhjl .l_t:nth-child(4) {
    .pointer_name {
      position: relative;
      left: 64px;
    }
  }
  
  .mainDiv.hjm_c {
    height: calc(100vh - 200px);
  
    .stage_c_r.main_3.hjm_zhjl_item {
      height: 100%;
  
      .el-carousel {
        padding-top: 0px;
  
        &:deep(.el-carousel__container) {
          height: 500px;
          width: 100%;
        }
      }
    }
  }
  
  .pointer_name {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin: 0 20px;
  
    >div {
      font-size: 25px;
      line-height: 25px;
      width: 250px;
      padding: 0 5px;
      text-align: left;
      border-top: 1px solid #EEE;
      border-left: 1px solid #EEE;
      border-right: 1px solid #EEE;
  
      &:last-child {
        border-bottom: 1px solid #EEE;
      }
  
      &:nth-child(2) {
        font-size: 20px;
        /* text-align: right; */
      }
  
      &:nth-child(3) {
        font-size: 20px;
        /* text-align: right; */
      }
    }
  }
  
  #huoYanDiv {
    width: 420px;
    height: 400px;
    z-index: 100;
    position: absolute;
    top: 160px;
    left: 50%;
    margin-left: -210px;
  }
  </style>